package ext.tianma.doc.forms;

import com.infoengine.object.IeObject;
import com.infoengine.object.factory.Group;
import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.windchill.enterprise.doc.forms.CreateDocFormProcessor;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.doc.util.MyDocUtil;
import ext.tianma.doc.util.TaskUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.PropertiesUtil;
import wt.content.*;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.org.WTPrincipal;
import wt.part.WTPart;
import wt.part.WTPartReferenceLink;
import wt.session.SessionHelper;
import wt.type.TypedUtility;
import wt.util.WTContext;
import wt.util.WTException;
import wt.util.WTProperties;

import java.beans.PropertyVetoException;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class CreateNewDocProcessor extends CreateDocFormProcessor {

	private static WTContext wtcontext = WTContext.getContext();
	private static boolean VERBOSE = false;
	private static String CLASSNAME = CreateNewDocProcessor.class.getName();
	private static final String RESOURCE = "ext.tianma.resource.ResourceRB";
	private static Locale LOCALE = null;
	// 设计转量产会议纪要文档内部名称
	private static final String TRANSFER_PRODUCTION = ".transferProductionMeeting";
	private static String softtype_ControlDocument = "cn.tianma.ControlDocument";// 受控PDF图纸

	private static List<String> timestampList = new ArrayList<String>();
	// 时间类型格式
	private static final String DATATIMEF_STR = "yyyy-MM-dd HH:mm";

	//配置文件路径
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "part" + File.separator + "config" + File.separator + "documentType.properties";

	private static PropertiesUtil ut = new PropertiesUtil(configFilePath);
	private static String processDocument = ut.getValueByKey("process.document");//工艺文件
	private static String specialDocument = ut.getValueByKey("special.document");//工艺文件

	static {
		// 集合中的属性需要特殊处理
		timestampList.add("FirstSampleRequiredTime");
		timestampList.add("CustomerApprovePlanTime");
		timestampList.add("DR3CSPhaseReviewPlanTime");
		timestampList.add("DR1ReviewPlanTime");
		timestampList.add("ESPhaseReviewCSPlanTime");
		timestampList.add("DR0KickoffActualTime");
		timestampList.add("FirstSamplePlanTime");
		timestampList.add("DR0RFQActualTime");
		timestampList.add("FirstProductionTime");

		try {
			WTProperties wtproperties = WTProperties.getLocalProperties();
			VERBOSE = wtproperties.getProperty("ext.tianma.doc.verbose", false);
			LOCALE = wtcontext.getLocale();
		} catch (Throwable throwable) {
			throwable.printStackTrace(System.err);
			throw new ExceptionInInitializerError(throwable);
		}
	}

	private StringBuffer getDocInfo(WTDocument doc) {

		StringBuffer stBf = new StringBuffer("Debug   ");

		if (doc != null) {
			stBf.append("docNumber:");
			stBf.append(doc.getNumber());
			stBf.append(" , ");
			stBf.append("docVersion:");
			stBf.append(doc.getVersionIdentifier());
			stBf.append(" , ");
			stBf.append("docContainer:");
			stBf.append(doc.getContainerName());
			stBf.append(" , ");
			stBf.append("docfolder:");
			stBf.append(doc.getFolderPath());
			stBf.append("\n");
		}

		return stBf;
	}

	@Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1)
			throws WTException {
		System.out.println(">>>>>>>>>>>>>  CreateNewDocProcessor   start");

		FormResult localFormResult = super.doOperation(arg0, arg1);

		Group group = null;
		Object localObject1 = ((ObjectBean) arg1.get(0)).getObject();
		WTDocument doc = null;
		if ((localObject1 instanceof WTDocument)) {
			doc = (WTDocument) localObject1;
		}
		
		String name = "";
		if (isObjectType(doc, "RFQ")) {

			// 查询中间表示创建where条件
			// String name = doc.getName();
			// 修改原因:以RFQ中的IBA属性"partRFQNumber"作为关联条件

			try {
				name = (String) IBAUtil.getIBAValue(doc, "partRFQNumber");

				if (name != null && !name.equals("")) {

					WTDocument wtDoc = MyDocUtil.getWTDocumentByIBAValue(
							"partRFQNumber", name);
					if (wtDoc != null) {
						System.out.println(getDocInfo(wtDoc));
						throw new WTException(
								"Debug   document does not exist...");
					}

				}
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("RFQ  name is  :" + name);
			String strWhere = "FD_BIANHAO='" + name + "'";

			System.out.println("RFQ  strWhere is  :" + strWhere);
			group = TaskUtil.queryRFQInfoByWhere(strWhere);

			if ((group == null)
					|| (!group.getGroup().getChildren().hasMoreElements())) {
				throw new WTException("从接口表中没有获取到当前RFQ的信息！");
			}
		} else {
			System.out.println("#################不是  RFQ 文档");
		}

		// 获取管理员权限
		WTPrincipal curUser = SessionHelper.manager.getPrincipal();
		SessionHelper.manager.setAdministrator();

		if (isObjectType(doc, "RFQ")) {
			doc = (WTDocument) LifeCycleHelper.service.setLifeCycleState(doc,
					State.RELEASED);
			int flag = 0;
			IeObject ieoRecord = null;
			String rfqName = "";
			for (Enumeration enum1 = group.getGroup().getChildren(); enum1
					.hasMoreElements();) {
				Hashtable table = new Hashtable();
				ieoRecord = (IeObject) enum1.nextElement();

				String finishedGoodSize = ieoRecord.getAtt("fd_cpccinch")
						.getDatum().toString();
				String productClassification = ieoRecord.getAtt("fd_cpfj")
						.getDatum().toString();

				String partNumber = ieoRecord.getAtt("fd_cpxh").getDatum()
						.toString().trim();
				String partName = ieoRecord.getAtt("fd_cpxh").getDatum()
						.toString().trim();

				String finishGoodName = ieoRecord.getAtt("fd_mc").getDatum()
						.toString().trim();

				if (rfqName.equals("")) {
					rfqName = partName;
				} else if (!rfqName.equals("")) {
					rfqName = rfqName + "," + partName;
				}

				Hashtable partIBATable = RFQCreateUtil
						.updateRFQDocRelatedFinishedGoodIBA(ieoRecord);
				if (VERBOSE) {

					StringBuffer partInfoBuffer = new StringBuffer("");
					partInfoBuffer.append("Debug RFQ创建   接口表中的数据    成品编号:");
					partInfoBuffer.append(partNumber);
					partInfoBuffer.append("\n");

					partInfoBuffer.append("Debug RFQ创建   接口表中的数据    成品名称:");
					partInfoBuffer.append(partName);
					partInfoBuffer.append("\n");

					Iterator<String> partIBATableIte = partIBATable.keySet().iterator();
					while (partIBATableIte.hasNext()) {
						String key = partIBATableIte.next();
						partInfoBuffer.append("Debug       ");
						partInfoBuffer.append(key);
						partInfoBuffer.append(" ==> ");
						partInfoBuffer.append(partIBATable.get(key));
						partInfoBuffer.append("\n");
					}
					System.out.println(partInfoBuffer.toString());
				}

				try {
					// 物料描述规则修改把原来的编号换成名称同时去掉最后的后缀
					// String[] strDesc = new
					// String[]{productClassification,partName,"TFT MODEL ID"};
					String[] strDesc = new String[] { productClassification,
							finishGoodName };

					String desc = genericIBA(strDesc);
					// 物料详细描述修改把原来的编号换成名称
					// String[] strDetail = new
					// String[]{finishedGoodSize,partName};
					String[] strDetail = new String[] { finishedGoodSize,
							finishGoodName };
					String detail = genericIBA(strDetail);

					System.out.println("Debug partRFQNumber  :"+ doc.getName());
					System.out.println("Debug partDescription  :" + desc);
					System.out.println("Debug partRFQNumber  :" + detail);

					// partRFQNumber的值由RFQ文档的名称变为IBA属性“”
					// partIBATable.put("partRFQNumber", doc.getName());
					partIBATable.put("partRFQNumber", name);
					partIBATable.put("partDescription", desc);
					partIBATable.put("materialDetails", detail);

					WTPart part = PartCommands.createFinishedGood(partNumber,finishGoodName, partIBATable, doc);
					//转变成持久化对象
					//Persistable persistancePart = PersistenceHelper.manager.refresh(part);
					/**
					 * @author xuge_ning
					 * @reason 新增RFQ与成品的关联关系
					 */
					System.out.println("建立关联关系开始。。。。");
					WTDocumentMaster docMaster= (WTDocumentMaster) doc.getMaster();
					WTPartReferenceLink link = WTPartReferenceLink.newWTPartReferenceLink(part,docMaster);
					PersistenceServerHelper.manager.insert(link);
					System.out.println("建立关联关系完成。。。。");
				} catch (Exception e) {
					throw new WTException(e);
				}
				Hashtable docTable = RFQCreateUtil.updateRFQDocIBA(ieoRecord);

				convertPartIBAValueByDate(docTable);

				if (flag == 0) {
					IBAUtil.setSoftTypeIBAValues(doc, docTable);
				}

				flag++;
			}
			Hashtable dt = new Hashtable();
			dt.put("finishedGoodType", rfqName);
			IBAUtil.setSoftTypeIBAValues(doc, dt);
		}
		SessionHelper.manager.setPrincipal(curUser.getName());
		System.out.println("<<<<<<<<<<  CreateNewDocProcessor   end");
		return localFormResult;
	}

	/**
	 * 将集合中的字符串转换成Timestamp类型
	 * 
	 * @param docTable
	 */
	public static void convertPartIBAValueByDate(Hashtable docTable) {
		if (docTable != null) {
			Enumeration enumeration = docTable.keys();
			DateFormat dateFormat = new SimpleDateFormat(DATATIMEF_STR);

			if (enumeration != null) {
				while (enumeration.hasMoreElements()) {
					Object object = enumeration.nextElement();

					if (object != null) {
						String key = (String) object;

						System.out.println("Debug   key:" + key);
						System.out.println("Debug   value:" + docTable.get(key));

						if (timestampList.contains(key)) {
							Object objectValue = docTable.get(key);

							if (objectValue != null) {
								String value = (String) objectValue;

								convertPartIBAValueByDate(docTable, dateFormat,
										key, value);
							}
						}
					}
				}
			}
		}
	}

	@Override
	public FormResult postProcess(NmCommandBean nmcommandBean, List list)
			throws WTException {

		FormResult formResult = super.postProcess(nmcommandBean, list);

		Object localObject1 = ((ObjectBean) list.get(0)).getObject();
		WTDocument doc = null;
		if ((localObject1 instanceof WTDocument)) {
			doc = (WTDocument) localObject1;
		}
		System.out.println("Debug doc:" + doc);
		String softtype = "";
		try {
			softtype = GenericUtil.getTypeId(doc);
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("=============isControlDocument softtype:"+softtype);

		if (doc != null) {
			QueryResult secondresult = ContentHelper.service.getContentsByRole(doc,
					ContentRoleType.SECONDARY);
			System.out.println("=============secondresult :"+secondresult.size());
			if (isTransferProductionMeeting(doc)) {

				try {
					boolean isTransferProductionMeeting = checkAttacheByDOC(doc);

					if (!isTransferProductionMeeting) {
						throw new WTException("请添加客户签回的IIS、SPEC封面");
					}
				} catch (PropertyVetoException e) {
					e.printStackTrace();
				}
			}else if(softtype.indexOf(softtype_ControlDocument)!=-1){
				System.out.println("=============isControlDocument softtype:"+softtype);

				//受控PDF图纸
				try {
					boolean isControlDocument = checkAttacheByDOC(doc);
					QueryResult qr = CoreUtil.getSecondaryContents(doc);
					System.out.println("=============isControlDocument:"+isControlDocument);
					if (!isControlDocument) {
						throw new WTException("请添加附件");
					}else if (qr.size() > 1){
						throw new WTException("受控-暂时只允许添加一个附件");
					}else{
							// 受控PDF文档移除附件
							doc = deleteContent(doc);
						}
				} catch (PropertyVetoException e) {
					e.printStackTrace();
				}
			}
			if(softtype.contains(processDocument) || softtype.contains(specialDocument) ){
				QueryResult qr = CoreUtil.getSecondaryContents(doc);
				System.out.println("============CreateDocFormProcessor=工艺文档文档移除附件:"+softtype);
				//工艺文档
				try {
					if (qr.size() > 1){
						throw new WTException("工艺文件-暂时只允许添加一个附件");
					}
					boolean isProcessDocument = checkAttacheByDOC(doc);
					System.out.println("==========CreateDocFormProcessor=是否是工艺文件==isProcessDocument:"+isProcessDocument);
					if (isProcessDocument) {
						// 工艺文档文档移除附件
						deleteContent(doc);
					}
				} catch (PropertyVetoException e) {
					e.printStackTrace();
				}
			}
		}

		return formResult;
	}

	/**
	 * 将集合中的字符串转换成Timestamp类型
	 * 
	 * @param docTable
	 * @param dateFormat
	 * @param key
	 * @param value
	 */
	private static void convertPartIBAValueByDate(Hashtable docTable,
			DateFormat dateFormat, String key, String value) {
		try {
			Date date = dateFormat.parse(value);
			Timestamp timestamp = new Timestamp(date.getTime());

			// 删除集合中原有的数据
			docTable.remove(key);
			// 添加转好格式的数据
			docTable.put(key, timestamp);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断对象类型是否为指定的内部关键字类型
	 * 
	 * @param object
	 *            对象；
	 * @param object
	 *            内部关键字；
	 * @return boolean 是指定的类型返回true；不是返回false
	 */
	public static boolean isObjectType(Object object, String objectType) {
		if (objectType == null || object == null || objectType.equals(""))
			return false;
		TypeIdentifier typeidentifier = TypedUtility.getTypeIdentifier(object);
		String typeName = typeidentifier.getTypename();
		if (typeName != null && typeName.indexOf(objectType) >= 0) {
			return true;
		}
		return false;
	}

	private String genericIBA(String[] values) {

		String strValue = "";
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				if (values[i] != null) {
					if (strValue.length() == 0) {
						strValue = values[i];
					} else {
						strValue = strValue + "-" + values[i];
					}

				}
			}
		}
		return strValue;
	}

	public static void main(String[] args) {
		String[] values = new String[] { "aaa", "bbb", "ccc" };
		String strValue = "";
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				if (values[i] != null) {
					if (strValue.length() == 0) {
						strValue = values[i];
					} else {
						strValue = strValue + "-" + values[i];
					}

				}
			}
		}
		System.out.println("Debug   number:" + strValue);
	}

	private static boolean isTransferProductionMeeting(WTDocument doc) {
		boolean isTransferProductionMeeting = false;

		if (doc == null) {
			return isTransferProductionMeeting;
		}

		isTransferProductionMeeting = TMTypeUtil.isATypeObject(doc,
				TRANSFER_PRODUCTION);

		return isTransferProductionMeeting;
	}

	/**
	 * 判断一下是否有附件
	 * 
	 * @param epm
	 * @return
	 * @throws WTException
	 * @throws PropertyVetoException
	 */
	public static boolean checkAttacheByDOC(WTDocument doc) throws WTException,
			PropertyVetoException {
		boolean flag = false;
		System.out.println("====checkAttacheByDOC doc:"+doc);

		if (doc == null) {
			return flag;
		}

		QueryResult qr = CoreUtil.getSecondaryContents(doc);
		System.out.println("====checkAttacheByDOC qr:"+qr.size());
		if (qr != null) {

			while (qr.hasMoreElements()) {
				ContentItem contentItem = (ContentItem) qr.nextElement();

				if (contentItem instanceof ApplicationData) {
					ApplicationData applicationData = (ApplicationData) contentItem;
					flag = true;
					System.out.println("Debug   applicationData:"
							+ applicationData);
					// 输出信息
				} else if (contentItem instanceof URLData) {
					URLData urlData = (URLData) contentItem;

					System.out.println("Debug   urlData:"
							+ urlData.getDisplayName());
					// 输出信息
				}
			}
		}

		return flag;
	}
	private static boolean isControlDocument(WTDocument doc) {
		boolean isControlDocument = false;

		if (doc == null) {
			return isControlDocument;
		}

		isControlDocument = TMTypeUtil.isATypeObject(doc,
				softtype_ControlDocument);

		return isControlDocument;
	}
	/**
	 * 移除受控PDF文档附件
	 * 
	 * @param doc
	 * @param data
	 * @return
	 */
	public static WTDocument deleteContent(WTDocument doc) {
		if (doc != null) {
            System.out.println("CreateDocFormProcessor-移除附件 beginning：" + doc.getName());
			QueryResult result;
			try {
				result = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);

				ApplicationData data = null;
				while (result.hasMoreElements()) {
					data = (ApplicationData) result.nextElement();

				}
				if (data != null) {
					ContentServerHelper.service.deleteContent(doc, data);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        System.out.println("CreateDocFormProcessor-移除附件 ending：" + doc.getName());

        return doc;
	}
}
